<template>
  <el-dialog :visible.sync="dialogShow" :before-close="check" title="新增" width="75%">
    <el-card class="box-card" :body-style="{ height: '90px' }">
      <div class="inputall">
        <div class="rolename">
          <span>角色名称：</span>
          <el-input
            v-model="roleName"
            class="roleNameInput"
            suffix-icon="el-icon-s-custom"
            size="small"
          />
        </div>
        <div class="rolenote">
          <span>备注：</span>
          <el-input
            v-model="roleNote"
            type="textarea"
            rows="2"
            class="roleNameInput"
            suffix-icon="el-icon-s-custom"
            size="small"
          />
        </div>
      </div>
    </el-card>
    <el-card>
      <el-tabs v-model="indexVal" tab-position="left">
        <el-tab-pane
          v-for="(item, index) in list"
          :key="item.id"
          :label="item.powerName"
          :name="item.powerName"
        >
          <!-- list是整个大数组 -->
          <el-checkbox-group v-model="checkList[index]">
            <div v-for="(menu, indexx) in item.children" :key="menu.id" class="menu">
              <!-- menu是每个模块的 -->
              <span>{{ menu.powerName }}</span>
              <div class="btnall">
                <el-checkbox
                  size="small"
                  :label="indexx"
                  @change="getAllVal(menu.children, index, indexx)"
                >全选</el-checkbox>
                <!-- btn是每个按钮 :label="menu.children" -->
                <!-- :disabled="menu.powerCode.indexOf('platPower') > -1 && checkList[index].length > 0 && lastIndex !== resultNum[indexx]" -->
                <el-checkbox
                  v-for="(btn, lastIndex) in menu.children"
                  :key="btn.id"
                  :label="btn.powerCode"
                  border
                  size="small"
                  @change="getIndex(indexx, lastIndex)"
                >{{ btn.powerName }}</el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
      <div class="btnpower">
        <el-button
          type="primary"
          size="mini"
          round
          style="width:15%"
          class="btnpowerFirst"
          @click="saveResult"
        >保存</el-button>
        <el-button
          plain
          round
          size="mini"
          style="width:15%"
          type="primary"
          @click="check"
        >取消</el-button>
      </div>
    </el-card>
  </el-dialog>
</template>
<script>
import { getNewList, saveRole } from '@/api/rolesetting'
export default {
  name: 'AddRole',
  props: {
    dialogTableNew: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogShow: false,
      indexVal: '用户管理',
      roleName: '',
      roleNote: '',
      list: null,
      status: [],
      resultNum: [],
      checkList: []
    }
  },
  watch: {
    dialogTableNew(newVal) {
      this.dialogShow = newVal
      this.loadNewList()
    }
  },
  methods: {
    getIndex(index, val) {
      console.log(val)
      this.resultNum[index] = val
    },
    // 请求新列表
    loadNewList() {
      getNewList().then(response => {
        // 创建数组
        var bigArrLen = response.data.length
        var lastData = []
        var bigArr = new Array(bigArrLen).fill([])
        this.resultNum = new Array(bigArrLen).fill(null)
        console.log(this.resultNum)
        this.checkList = bigArr
        var req = response.data
        for (let i = 0; i < req.length; i++) {
          var newData = bigArr[i].concat(req[i].children)
          lastData.push(newData)
        }
        for (let j = 0; j < lastData.length; j++) {
          lastData[j].fill(true)
        }
        this.status = lastData
        const { data } = response
        this.list = data
      }).catch(() => {
        this.$message({
          message: '请求列表失败，请重试',
          type: 'error'
        })
      })
    },
    check: function() {
      this.$emit('closeNewDialog')
      this.roleName = ''
      this.roleNote = ''
      setTimeout(() => {
        this.indexVal = '用户管理'
      }, 1000)
      this.dialogShow = false
    },
    // 保存
    saveResult: function() {
      var result = []
      // 合并数组
      this.checkList.forEach(function(item) {
        result.push(...item)
      })
      // 去除全选索引
      var newResult = []
      if (result.length > 0) {
        result.forEach(function(item) {
          if (item !== null && item !== '' && isNaN(item)) {
            newResult.push(item)
          }
        })
        var newList = [] // 重组后的列表
        var systemMenuList = [] // 重组后的system && 重组后的menu列表列表
        // list重组
        this.list.forEach(function(item) {
          if (item.children && item.children.length > 0) {
            item.children.forEach(function(params) {
              if (params.children && params.children.length > 0) {
                params.children.forEach(function(val) {
                  newList.push(val)
                })
                delete params.children
                systemMenuList.push(params)
              }
            })
            delete item.children
            systemMenuList.push(item) // 把system存入
          }
        })
        // 开始查找
        var lastValue = []
        newList.forEach(function(relVal) {
          newResult.forEach(function(relSmall) {
            if (relVal.powerCode === relSmall) {
              lastValue.push(relVal)
            }
          })
        })
        var arrAll = []
        for (let i = 0; i < systemMenuList.length; i++) {
          for (let j = 0; j < lastValue.length; j++) {
            const systemIndex = lastValue[j].parentCode.indexOf('-')
            const system = lastValue[j].parentCode.substring(0, systemIndex)
            const menuIndex = lastValue[j].parentCode
            if (system === systemMenuList[i].powerCode && systemMenuList[i].powerType === 'system') {
              arrAll.push(systemMenuList[i])
              break
            }
            if (menuIndex === systemMenuList[i].powerCode && systemMenuList[i].powerType === 'menu') {
              arrAll.push(systemMenuList[i])
              break
            }
          }
        }
        var lastAllResult = lastValue.concat(arrAll)
        console.log(lastAllResult)
        var lastDataResult = {
          name: this.roleName,
          remark: this.roleNote,
          powers: lastAllResult
        }
        console.log(lastDataResult)
        // business-platPower
        saveRole(lastDataResult).then(res => {
          if (res.resultCode === '0000') {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.check()
          } else {
            this.loadNewList()
          }
        })
      } else {
        // 没权限
        lastValue = []
      }
      // ajax
      // this.check()
    },
    // 全选
    getAllVal: function(val, num, indexx) {
      this.resultNum[indexx] = null
      var that = this
      var status = this.status[num][indexx]
      // 全选
      if (val.length > 0) {
        if (status) {
          val.forEach(function(item) {
            if (that.checkList[num].indexOf(item.powerCode) === -1) {
              that.checkList[num].push(item.powerCode)
            }
          })
          this.status[num][indexx] = false
        } else {
          val.forEach(function(item) {
            var rank = that.checkList[num].indexOf(item.powerCode)
            if (rank !== -1) {
              that.checkList[num].splice(rank, 1)
            }
          })
          this.status[num][indexx] = true
        }
      // console.log(this.checkList)
      }
    }
  }
}
</script>
<style scoped>
  .checkbox-per{
    margin-top: -43px;
    padding-left: 180px;
  }
  .btnList{
    width: 200px;
    text-align: center;
    margin: 0 auto;
  }
  .btn{
    margin-bottom: -20px !important;
    padding-bottom: 10px;
  }
  .marginBtn{
    margin-left: 30px;
  }
  .leftPosition{
    margin-left: 20px;
  }
  .add{
    font-size: 100px;
  }
  .inputall{
    display: flex;
    width: 100%;
    height: 32px;
    line-height: 32px;
    justify-content: space-around;
  }
  .rolename, .rolenote{
    font-weight: bold;

  } /* ,.rolenote:before */
  .rolename::before{
    content: '*';
    float: left;
    color: red;
  }
  .rolename span, .rolenote span{
    float: left;
    width: 80px;
    display: block;
  }
  .box-card{
    margin-bottom: 10px;
    margin-top: -20px;
  }
  .roleNameInput{
    float: left;
    width: 200px;
  }
  .menu{
    width: 98%;
    margin: 15px 5px 5px 5px;
    /* box-shadow: 0 1px 2px 0 rgba(0,0,0,.1); */
    border-bottom: 1px solid #ccc;
    padding: 10px 10px 0px 10px;
  }
  .menu span{
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 13px;
    display: inline-block;
  }

  .btnall{
    margin-left: 10px;
  }
  .btnpower{
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  .btnpowerFirst{
    margin-right: 10px
  }
</style>
<style>
  .el-checkbox.is-bordered+.el-checkbox.is-bordered{
    margin-left: 0 !important;
    margin-bottom: 10px !important;
  }
  .el-checkbox.is-bordered.el-checkbox--small{
    margin-bottom: 10px !important;
  }
</style>
